const navigateTo = ({ url, params, success, fail, complete }) => {
  // 如果存在 params，则拼接参数到 url
  if (params && typeof params === "object" && Object.keys(params).length > 0) {
    const queryString = Object.keys(params)
      .map(
        (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
      )
      .join("&");
    url += (url.includes("?") ? "&" : "?") + queryString;
  }

  // 调用 uni.navigateTo
  uni.navigateTo({
    url,
    success: (res) => {
      console.log("跳转成功", url);
      success && success(res);
    },
    fail: (err) => {
      console.error("跳转失败", err);
      fail && fail(err);
    },
    complete: (res) => {
      complete && complete(res);
    },
  });
};

export function to(url, params, type) {
  if (!uni.getStorageSync("USER-INFO")) {
    uni.navigateTo({
      url: "/pages/login/index",
      success: () => console.log("跳转成功"),
      fail: (err) => console.error("跳转失败", err),
    });
    return;
  }
  if (type === "tabbar") {
    let newUrl = "";

    uni.switchTab({
      url: url,
      params,
      success: () => console.log("跳转成功"),
      fail: (err) => console.error("跳转失败", err),
    });
  } else {
    navigateTo({
      url,
      params,
      success: () => console.log("跳转成功"),
      fail: (err) => console.error("跳转失败", err),
    });
  }
}
